package sword;

/**
 * @author longzj
 */
public class FindMaxPrefix {

    public static void main(String[] args) {
        String[] array = {"flow", "flower", "float"};
        FindMaxPrefix prefix = new FindMaxPrefix();
        System.out.println("max common prefix is " + "\"" + prefix.longestCommonPrefix(array) + "\"");
    }


    private String longestCommonPrefix(String[] strs) {
        int arrayLength = strs.length;
        String result = "";
        char firstChar = '-';
        boolean allMatch = false;
        int count = 0;
        while (true) {
            for (int index = 0; index < arrayLength; index++) {
                String tmp = strs[index];
                int tmpLength = tmp.length();
                if (tmpLength == 0) {
                    result = "";
                    break;
                } else if (tmpLength == count) {
                    break;
                }
                char tmpChar = tmp.charAt(count);
                if (index == 0) {
                    firstChar = tmpChar;
                } else if (index == arrayLength - 1) {
                    if (firstChar == tmpChar) {
                        allMatch = true;
                    }
                } else if (firstChar != tmpChar) {
                    break;
                }
            }
            if (allMatch) {
                result += String.valueOf(firstChar);
                allMatch = false;
                count++;
            } else {
                break;
            }

        }
        return result;
    }
}
